#!/usr/bin/env python
# encoding: utf-8
"""
tableserver.py

Created by 黄 冬 on 2007-12-20.
Copyright (c) 2007 __MyCompanyName__. All rights reserved.
"""
from twisted.internet import reactor,defer
from twisted.internet.protocol import Protocol, ServerFactory
from twisted.protocols.basic import Int16StringReceiver
import logging.config

log = logging.getLogger('xbaytable.tools.tableserver')
#logging.basicConfig(level=logging.ERROR)
#logging.basicConfig(level=logging.WARNING)
logging.basicConfig(level=logging.DEBUG)

from xbaytable.conf import *
from xbaytable.utils.tablemsg import *

class TableServerProtocol(Int16StringReceiver):
    """实现table protocol"""
    def stringReceived(self, msg):
        """有人发送数据来了"""
        command,sequence_id=self.process.recv_head(msg[0:4])
        self.sendwin.append(sequence_id)
        log.debug('recv command %s,sequence %s'%(command['command_name'],sequence_id))
        if (not self.bind and command['command_id'] <> 1):
            #如果没有bind认证通过，还不是一个bind的请求，哪么关闭这个新来的连接
            self.transport.loseConnection()
        elif(command['command_id']==1):
            if self.process.process_bind_table(self,command,sequence_id,msg[4:])==0 :
                self.bind=True
            else:
                #认证不通过，断了丫的连接
                self.transport.loseConnection()
        else:
            #通过认证了，可以干想干的事了，按照command_name，做对应的process事
            d = self.process_command(command,sequence_id,msg)
    
    def process_command(self,command,sequence_id,msg):
        """处理发来的请求"""
        d = defer.Deferred()
        eval('self.process.process_%s(self,command,sequence_id,msg[4:])'%command['command_name'])
        return d

    def connectionMade(self):
        """有人连接上来了，记入列表，设置它还没有bind成功"""
        log.debug('client connect to self...')
        # 发送窗口
        self.sendwin = []
        # 客户端是否bind认证通过
        self.bind = False
        #处理消息的对象进行初始化
        self.process =self.factory.process()

    def connectionLost(self, reason):
        log.debug('client lost...')
        #self.factory.clients.remove(self)

class TableServerFactory(ServerFactory):
    """客户端连接工厂类"""
    protocol=TableServerProtocol
    
    def __init__(self,process):
        self.process=process

if __name__ == '__main__':
    sendnum = 1
    reactor.listenTCP(TABLE_SERVER_PORT, TableServerFactory(ProcessMessage))
    reactor.run()
